<?php

namespace App\Http\Controllers\Admin;

use App\Model\Role;
use App\Model\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Validator;

class UserController extends Controller
{
    /**
     * 获取列表页
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //获取搜索数据
        $username = trim($request->get('username'));
        // 获取user表全部数据
        if (isset($username)) {
            $user = User::where('user_name', 'like', "%" . $username . "%")->paginate(10);
        } else {
            $user = User::paginate(10);
        }
        foreach ($user as $v){
            $v = $v->role;
        }
        return view('admin.user.member_list', compact('user'));
    }

    /**
     * 展示一个添加页面
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.user.member_add');
    }

    /**
     * 执行添加操作
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->except('_token');
//       1.数据合法性验证
        $rule = [
            'user_name' => 'required',
            'user_pass' => 'required|confirmed',
            'user_pass_confirmation' => 'required|same:user_pass',
        ];
        $messages = [
            'user_name.required' => '用户名不能为空!',
            'user_pass.required' => '密码不能为空!',
            'user_pass.confirmed' => '2次输入密码不一致!',
            'user_pass_confirmation.required' => '确认密码不能为空!',
        ];
        $validator = Validator::make($request->all(), $rule, $messages);
        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            $res = [
                'status' => 1,
                'data' => $errors,
                'message' => '验证失败'
            ];

        }
        //保存数据到数据库
        $user = new User();
        //判断用户是否已经注册
        $userinfo = $user->where('user_name', $input['user_name'])->first();
        if (!empty($userinfo)) {
            $res = [
                'status' => 1,
                'data' => ['用户名已经存在！'],
                'message' => '注册失败'
            ];
            return json_encode($res);
        }
        $user->user_name = $input['user_name'];
        $user->user_pass = Hash::make($input['user_pass']);
        $status = $user->save();


        if ($status) {
            //设想  先查找员工该角色是否存在 如果不存在 就创建该角色  权限 为空 以后优化
            //默认添加角色为 员工
            DB::table('user_role')->insert(['user_id'=>$user->user_id,'role_id'=>9]);
            $res = [
                'status' => 0,
                'data' => [],
                'message' => '注册成功'
            ];
        } else {
            $res = [
                'status' => 1,
                'data' => ['注册失败，请检查数据库'],
                'message' => '注册失败'
            ];
        }
        return json_encode($res);
    }

    /**
     * 显示一条数据
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 返回修改页面
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //通话id 获取数据信息
        $user = User::find($id);
        //获取角色信息
        $role = Role::all();
        //获取角色拥有的数据
        $own_role = $user->role;
        $own_roleid = [];
        foreach ($own_role as $v){
            $own_roleid[] = $v->id;
        }
        return view("admin.user.member_edit", compact('user', 'role','own_roleid'));
    }

    /**
     * 执行修改操作
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        $input = $request->except('_token');
//       1.数据合法性验证
        $rule = [
            'user_pass' => 'confirmed',
            'user_pass_confirmation' => 'same:user_pass',
            'roleid' => 'required',
        ];
        $messages = [
            'user_pass.confirmed' => '2次输入密码不一致!',
            'roleid.required' => '角色必须选择',
        ];
        $validator = Validator::make($request->all(), $rule, $messages);
        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            $res = [
                'status' => 1,
                'data' => $errors,
                'message' => '验证失败'
            ];

        }
        $status = false;
        //1.如果存在密码修改了   就保存密码
        if (isset($input['user_pass'])) {
            $user = new User();
            $status = $user->where('user_id', $input['user_id'])->update(['user_pass' => Hash::make($input['user_pass'])]);
        }
        //保存新的角色信息
        if (isset($input['roleid'])) {
            $user_role = [];
            foreach ($input['roleid'] as $v) {
                $user_role[] = [
                    'user_id' => $input['user_id'],
                    'role_id' => $v
                ];
            }
            $status = DB::table('user_role')->insert($user_role);
        }

        if ($status) {
            $res = [
                'status' => 0,
                'data' => [],
                'message' => '修改成功'
            ];

        } else {
            $res = [
                'status' => 1,
                'data' => ['修改失败'],
                'message' => '修改失败'
            ];
        }
        return json_encode($res);


    }

    /**
     * 执行删除操作
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user = new User();
        $status = $user->where('user_id', $id)->delete();
        if ($status) {
            $res = [
                'status' => 0,
                'data' => [],
                'message' => '删除成功'
            ];

        } else {
            $res = [
                'status' => 1,
                'data' => ['删除失败'],
                'message' => '删除失败'
            ];
        }
        return json_encode($res);
    }

    //修改用户状态
    public function checkStatus(Request $request)
    {
        $input = $request->except('_token');
        $user = new User();
        $status = $user->where('user_id', $input['user_id'])->update(['status' => $input['status']]);
        if ($status) {
            $res = [
                'status' => 0,
                'data' => [],
                'message' => '修改成功'
            ];

        } else {
            $res = [
                'status' => 1,
                'data' => ['修改失败！'],
                'message' => '修改失败'
            ];
        }
        return json_encode($res);
    }

    //批量删除
    public function deleteAll(Request $request)
    {

        $user = new User();
        $status = $user->whereIn('user_id', $request->get('ids'))->delete();
        if ($status) {
            $res = [
                'status' => 0,
                'data' => [],
                'message' => '批量删除成功'
            ];

        } else {
            $res = [
                'status' => 1,
                'data' => ['批量删除失败！'],
                'message' => '批量删除失败'
            ];
        }
        return json_encode($res);
    }
}
